import cv2
import numpy as np

if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread('image.jpg')
    if image_np is None:
        print("无法读取图片，请检查路径")
        exit()

    # 2. HSV空间转换
    hsv_image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)

    # 3. 制作“越”字的蓝色掩膜（精准匹配其颜色范围）
    yue_blue_low = np.array([95, 60, 60])
    yue_blue_high = np.array([125, 255, 255])
    yue_mask = cv2.inRange(hsv_image_np, yue_blue_low, yue_blue_high)

    # 4. 制作原目标掩膜（红、黄）
    red_low1 = np.array([0, 43, 46])
    red_high1 = np.array([10, 255, 255])
    mask1 = cv2.inRange(hsv_image_np, red_low1, red_high1)

    red_low2 = np.array([156, 43, 46])
    red_high2 = np.array([180, 255, 255])
    mask2 = cv2.inRange(hsv_image_np, red_low2, red_high2)

    yellow_low = np.array([26, 43, 46])
    yellow_high = np.array([34, 255, 255])
    mask3 = cv2.inRange(hsv_image_np, yellow_low, yellow_high)

    mask_temp = cv2.bitwise_or(mask1, mask2)
    color_mask = cv2.bitwise_or(mask_temp, mask3)

    # 5. 制作灰色掩膜
    gray_low = np.array([0, 0, 46])
    gray_high = np.array([180, 43, 220])
    gray_mask = cv2.inRange(hsv_image_np, gray_low, gray_high)

    # 6. 形态学开运算（缩小核尺寸，避免过度腐蚀）
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    open_yue_mask = cv2.morphologyEx(yue_mask, cv2.MORPH_OPEN, kernel, iterations=5)
    open_color_mask = cv2.morphologyEx(color_mask, cv2.MORPH_OPEN, kernel, iterations=1)
    open_gray_mask = cv2.morphologyEx(gray_mask, cv2.MORPH_OPEN, kernel, iterations=1)

    # 7. 合并掩膜（确保“越”字与其他目标区域不冲突）
    total_mask = cv2.bitwise_or(open_yue_mask, open_color_mask)
    total_mask = cv2.bitwise_or(total_mask, open_gray_mask)

    # 8. 颜色替换：分区域设置颜色
    result = image_np.copy()
    for i in range(result.shape[0]):
        for j in range(result.shape[1]):
            if open_yue_mask[i, j] == 255:
                result[i, j] = (143, 82, 17)  # “越”字目标颜色
            elif open_color_mask[i, j] == 255:
                result[i, j] = (143, 82, 17)  # 其他红/黄区域目标颜色
            elif open_gray_mask[i, j] == 255:
                result[i, j] = (255, 255, 255)  # 灰色→白色

    # 9. 图片输出
    cv2.imshow('result', result)
    cv2.imwrite('nulxingy.png', result)
    cv2.waitKey(0)
